<?php
namespace common\workerman;

//use common\utils\Json;
use GatewayWorker\Lib\Gateway;
use think\worker\Events;
use Workerman\Worker;

class GatewayEvents extends Events
{
    /**
     * onConnect 事件回调
     * 当客户端连接上gateway进程时(TCP三次握手完毕时)触发.
     *
     * @param int $client_id
     */
    public static function onConnect($client_id)
    {
        $response = [
            'type' => 'connect',
            'client_id' => $client_id,
        ];
        Gateway::sendToCurrentClient(json_encode($response));
    }

    /**
     * onWebSocketConnect 事件回调
     * 当客户端连接上gateway完成websocket握手时触发.
     *
     * @param int   $client_id 断开连接的客户端client_id
     * @param mixed $data
     */
    public static function onWebSocketConnect($client_id, $data)
    {
        $response = [
            'type' => 'web_socket_connect',
            'client_id' => $client_id,
            'data' => $data,
        ];
        Gateway::sendToCurrentClient(json_encode($response));
    }

    /**
     * onMessage 事件回调
     * 当客户端发来数据(Gateway进程收到数据)后触发.
     *
     * @param int   $client_id
     * @param mixed $data
     */
    public static function onMessage($client_id, $data)
    {
        $response = [
            'type' => 'message',
            'client_id' => $client_id,
            'data' => json_decode($data),//Json::decode($data),
        ];

        Gateway::sendToCurrentClient(json_encode($response));
    }

    /**
     * onClose 事件回调 当用户断开连接时触发的方法.
     *
     * @param int $client_id 断开连接的客户端client_id
     */
    public static function onClose($client_id)
    {
        $data = [
            'type' => 'close',
            'client_id' => $client_id,
        ];
        GateWay::sendToClient($client_id, json_encode($data));
    }

    /**
     * onWorkerStop 事件回调
     * 当businessWorker进程退出时触发。每个进程生命周期内都只会触发一次。
     */
    public static function onWorkerStop(Worker $businessWorker)
    {
        echo "WorkerStop\n";
    }
}